﻿#include "voicemsg.h"
#include "ui_voicemsg.h"

VoiceMsg::VoiceMsg(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::VoiceMsg) {
    ui->setupUi(this);
}

VoiceMsg::VoiceMsg(QString absoluteAvatorPath, QString time, QString absoluteVoicePath, QWidget *parent) :
    QWidget(parent), ui(new Ui::VoiceMsg) {
    ui->setupUi(this);
    ui->time->setText(time);
    ui->avator->setScaledContents(true);
    ui->avator->setFixedSize(50, 50);
    ui->avator->setPixmap(QPixmap(absoluteAvatorPath).scaled(ui->avator->size(), Qt::KeepAspectRatio));

    this->absoluteVoicePath = absoluteVoicePath;

    player = new QMediaPlayer;
    connect(player, SIGNAL(positionChanged(qint64)), this, SLOT(positionChanged(qint64)));
    connect(player,SIGNAL(durationChanged(qint64)),this,SLOT(durationChanged(qint64)));
    player->setMedia(QUrl::fromLocalFile(absoluteVoicePath));
    player->setVolume(30);

    ui->avator->setStyleSheet("background:transparent;");
    ui->time->setStyleSheet("border-radius:10px;"
                            "background:transparent;"
                            "border-radius:5px;");
}


VoiceMsg::~VoiceMsg()
{
    delete ui;
}

void VoiceMsg::on_playBtn_clicked() {
    if (isPlaying) {
        player->pause();
        ui->playBtn->setText(QString("🔈"));
    } else {
        player->play();
        ui->playBtn->setText(QString("🔊"));
    }
    isPlaying = !isPlaying;
}

void VoiceMsg::on_stopBtn_clicked() {
    player->stop();
}

void VoiceMsg::positionChanged(qint64 position) {
    if(ui->horizontalSlider->isSliderDown()) return;
    ui->horizontalSlider->setSliderPosition(position);
    int secs = position / 1000;
    int mins = secs / 60;
    secs = secs % 60;
    positionTime = QString::asprintf("%d:%d",mins,secs);
    ui->playdura->setText(positionTime + " / " + durationTime);
}

void VoiceMsg::durationChanged(qint64 duration) {
    ui->horizontalSlider->setMaximum(duration);
    int secs = duration / 1000;
    int mins = secs / 60;
    secs = secs % 60;
    durationTime = QString::asprintf("%d:%d",mins,secs);
    ui->playdura->setText(positionTime + " / " + durationTime);
}

void VoiceMsg::on_horizontalSlider_valueChanged(int value) {
    if(ui->horizontalSlider->isSliderDown()) player->setPosition(value);
}
